package com.mall.shopping.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.shopping.PagedSelectProductService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.ProductConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.AllProductRequest;
import com.mall.shopping.dto.AllProductResponse;
import com.mall.shopping.dto.ProductDto;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

//分⻚查询商品列表

@Service(interfaceClass = PagedSelectProductService.class)
@Component
public class PagedSelectProductImp implements PagedSelectProductService {
    @Autowired
    ItemMapper itemMapper;
    @Autowired
    ProductConverter productConverter;

    @Override
    public AllProductResponse queryPageProduct(AllProductRequest request) {
        PageHelper.startPage(request.getPage(),request.getSize());
        AllProductResponse response = new AllProductResponse();
        try {
            request.requestCheck();
        }catch (ValidateException e){
            response.setCode(ShoppingRetCode.REQUISITE_PARAMETER_NOT_EXIST.getCode());
            response.setMsg("价格参数不正确");
            return response;
        }
        Example example = new Example(Item.class);
        if (request.getSort().equals("1")){
            example.setOrderByClause("price asc");
        }else if (request.getSort().equals("-1")){
            example.setOrderByClause("price desc");
        }else {
            example.setOrderByClause("price asc");
        }
        if (request.getPriceGt() != null && request.getPriceLte() != null){
            example.createCriteria().andBetween("price",request.getPriceGt(),request.getPriceLte());
        }
        if (request.getPriceGt() == null && request.getPriceLte() != null){
            example.createCriteria().andBetween("price",0,request.getPriceLte());
        }
        if (request.getPriceGt() != null && request.getPriceLte() == null){
            example.createCriteria().andGreaterThan("price",request.getPriceGt());
        }
        if (request.getPriceGt() ==  request.getPriceLte() ){
            example.createCriteria().andEqualTo("price",request.getPriceGt());
        }
        List<Item> items = itemMapper.selectByExample(example);
        List<ProductDto> productDtos = productConverter.items2Dto(items);
        PageInfo pageInfo = new PageInfo(items);
        long total = pageInfo.getTotal();
        response.setProductDtoList(productDtos);
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        response.setTotal(total);
        return response;
    }
}
